//
//  ViewController.m
//  liulanqi
//
//  Created by HappyMilk 02 on 2017/1/7.
//  Copyright © 2017年 HappyMilk 02. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "MJLocaStorage.h"
#import "MJHistoryController.h"
#import "Public.h"
#import "Reachability.h"

#import "WeChatQQStaticLibHeader.h"


#import "MJMainModel.h"

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define HEXCOLOR(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


#define HISTORY_URL @"historyurl"
#define COLLECTE_URL @"collecturl"
#define PROFROS_WIDTH 2


#define HOME_URL @"https://www.hao123.com"

@interface ViewController ()<WKNavigationDelegate,UIScrollViewDelegate,UISearchBarDelegate>

@property (strong, nonatomic) WKWebView* webview;

@property (weak, nonatomic) IBOutlet UIButton *btn_back;
@property (weak, nonatomic) IBOutlet UIButton *btn_goto;
@property (weak, nonatomic) IBOutlet UIButton *btn_home;
@property (weak, nonatomic) IBOutlet UIButton *btn_collect;
@property (weak, nonatomic) IBOutlet UISearchBar *serchbar;
@property (weak, nonatomic) IBOutlet UIView *view_scerch;
@property (weak, nonatomic) IBOutlet UIView *view_web;

//更多面板
@property (weak, nonatomic) IBOutlet UIButton *btn_collection;
@property (weak, nonatomic) IBOutlet UIView *view_more;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *view_bottem_high;
@property (weak, nonatomic) IBOutlet UIButton *btn_night;

//屏幕亮度
@property (assign, nonatomic) CGFloat  oldBrightness;

@property (weak, nonatomic) IBOutlet UIView *view_zhedang;

@property (nonatomic ,strong) MJProgressHUD *hud;


@property (nonatomic, strong) CALayer *progressView;
@property (nonatomic, assign) NSUInteger loadCount;

@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
}

- (void)internationalChange{
    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:HOME_URL]]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //历史记录点击通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(historyAction:) name:@"dianji" object:nil];
    //网络变化通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(internationalChange) name:@"youwangluo" object:nil];
    
    
    _view_zhedang.hidden = YES; //遮挡
    _oldBrightness = [[UIScreen mainScreen] brightness];//屏幕亮度
    
    
    
    _webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-44-49)];
    _webview.navigationDelegate = self;
    _webview.scrollView.delegate = self;
    [_view_web addSubview:_webview];
    
    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:HOME_URL]]];
    [_webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    
    //进度条
    UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), PROFROS_WIDTH)];
    progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:progress];
    
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, PROFROS_WIDTH);
    layer.backgroundColor = [UIColor blueColor].CGColor;
    [progress.layer addSublayer:layer];
    self.progressView = layer;

    
}

- (void)observeValueForKeyPath:(NSString* )keyPath ofObject:(id)object change:(NSDictionary* )change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.opacity = 1;
        //不要让进度条倒着走...有时候goback会出现这种情况
        if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
            return;
        }
        self.progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], PROFROS_WIDTH);
        if ([change[@"new"] floatValue] == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.frame = CGRectMake(0, 0, 0, PROFROS_WIDTH);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }

}





- (void)historyAction:(NSNotification *)noti{
    
    NSString *url = [noti.userInfo objectForKey:@"urlstr"];
    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

- (IBAction)goBack:(id)sender {
    
    UIColor * color = HEXCOLOR(0x007AFF);
    SHOW_LOGIN_VIEW_CONTROLLER(color);

    if (_webview.canGoBack) {
        [_webview goBack];
    }
}

- (IBAction)gofant:(id)sender {
    
    UIColor * color = HEXCOLOR(0x007AFF);
    SHOW_LOGIN_VIEW_CONTROLLER(color);
    
    if (_webview.canGoForward) {
        [_webview goForward];
    }
}

//返回其实页面
- (IBAction)home:(id)sender {
    
    UIColor * color = HEXCOLOR(0x007AFF);
    SHOW_LOGIN_VIEW_CONTROLLER(color);
    
    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:HOME_URL]]];
}
- (IBAction)paopermoreview:(id)sender {
    
    UIColor * color = HEXCOLOR(0x007AFF);
    SHOW_LOGIN_VIEW_CONTROLLER(color);
    
    _view_zhedang.hidden = NO;
    _view_zhedang.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        _view_zhedang.alpha = 0.4;
        CGRect frame = (CGRect){ 0, SCREEN_HEIGHT-170, SCREEN_WIDTH, 170};
        _view_more.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark --- 更多面板功能
- (IBAction)addCollect:(id)sender {
    
    NSDictionary *dic = @{@"title":_webview.title,@"url":_webview.URL.absoluteString};
    NSMutableArray *urls = [[MJLocaStorage getArrayFile:COLLECTE_URL] mutableCopy];
    [urls addObject:dic];
    [MJLocaStorage saveArrayFile:urls AndFileName:COLLECTE_URL];
    
    [MJProgressHUD showAlertWithString:@"收藏成功"];
    
    [self transformMoreview:nil];
    
}
- (IBAction)collectList:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    MJHistoryController *vc = [sb instantiateViewControllerWithIdentifier:@"MJHistoryController"];
    vc.type = NO;
    [self.navigationController pushViewController:vc animated:YES];
    
    [self transformMoreview:nil];
}
- (IBAction)reloadWebview:(id)sender {
    
    [_webview reload];
    [self transformMoreview:nil];
}
- (IBAction)historyList:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    MJHistoryController *vc = [sb instantiateViewControllerWithIdentifier:@"MJHistoryController"];
    vc.type = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
    [self transformMoreview:nil];
}
- (IBAction)nightType:(UIButton *)sender {
    
    if (sender.selected) {
        [[UIScreen mainScreen] setBrightness: _oldBrightness];
        _btn_night.selected = NO;
        [_btn_night setImage:[UIImage imageNamed:@"night_type"] forState:UIControlStateNormal];
        [self transformMoreview:nil];
    }else{
        [[UIScreen mainScreen] setBrightness: 0.2];
        _btn_night.selected = YES;
        [_btn_night setImage:[UIImage imageNamed:@"night_sel"] forState:UIControlStateNormal];
        [self transformMoreview:nil];
    }
}
- (IBAction)setup:(id)sender {
    
    _hud = [[MJProgressHUD alloc] init];
    [_hud startActive];
    [self performSelector:@selector(brnAction) withObject:nil afterDelay:1];
}
- (void)brnAction{
    
    [_hud stopActive];
    [MJProgressHUD showAlertWithString:@"清除缓存成功"];
}

- (IBAction)transformMoreview:(id)sender {
    
    [UIView animateWithDuration:0.3 animations:^{
        _view_zhedang.alpha = 0;
        CGRect frame = (CGRect){ 0, SCREEN_HEIGHT, SCREEN_WIDTH, 170};
        _view_more.frame = frame;
    } completion:^(BOOL finished) {
        _view_zhedang.hidden = YES;
    }];
}




#pragma mark --- UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    UIColor * color = HEXCOLOR(0x007AFF);
    SHOW_LOGIN_VIEW_CONTROLLER(color);
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    _serchbar.text = @"https://";
    return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if (searchBar.text) {
        [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_serchbar.text]]];
        searchBar.text = @"";
    }
    [self.serchbar resignFirstResponder];
}


#pragma mark --- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self.serchbar resignFirstResponder];
    _serchbar.text = @"";
}


#pragma mark --- WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
    //NSLog(@"title --- %@",webView.title);
    [self goBackOrGointo];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
//    NSString *string = @"document.documentElement.innerHTML";
//    [webView evaluateJavaScript:string completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        
//        NSLog(@"html ---- %@",response);
//        
//    }];
    //NSString *htmlstr = [webView stringByEvaluatingJavaScriptFromString:string];

    if (webView.title != nil && ![webView.title  isEqual: @""]) {
        NSLog(@"title --- %@",webView.title);
        NSDictionary *dic = @{@"title":webView.title,@"url":webView.URL.absoluteString};
        NSMutableArray *urls = [[MJLocaStorage getArrayFile:HISTORY_URL] mutableCopy];
        [urls addObject:dic];
        [MJLocaStorage saveArrayFile:urls AndFileName:HISTORY_URL];
    }
    [self goBackOrGointo];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{

    [self goBackOrGointo];
}


/*
 * 前进，返回按钮是否可点击
 */
- (void)goBackOrGointo{

    if (_webview.canGoBack) {
        _btn_back.enabled = YES;
    }else{
        _btn_back.enabled = NO;
    }
    if (_webview.canGoForward) {
        _btn_goto.enabled = YES;
    }else{
        _btn_goto.enabled = NO;
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
